package cn.jwis.exception;
import cn.jwis.domain.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * controller 增强器 处理controller层所有exception拦截
 * 
 * @author samuel
 * @since 2017/11/8
 */
@ControllerAdvice
public class BaseControllerAdvice {
	public static final Logger logger = LoggerFactory.getLogger(BaseControllerAdvice.class);

	/**
	 * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
	 * 
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder) {
	}

	/**
	 * 全局异常捕捉处理
	 * 
	 * @param ex
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = Exception.class)
	public Result errorHandler(Exception ex) {
		// ex.printStackTrace();
		StackTraceElement[] stackTrace = ex.getStackTrace();
		Exception exception = new Exception(ex.getMessage());
		exception.setStackTrace(stackTrace);
		logger.error(ex.fillInStackTrace().toString(), exception);
		Result responseEntity = new Result();
		responseEntity.setCode(-1);
		responseEntity.setMsg(ex.fillInStackTrace().toString());
		return responseEntity;
	}

	/**
	 * 全局异常捕捉处理
	 * 
	 * @param ex
	 * @return
	 */
	@ResponseBody
	@ExceptionHandler(value = BaseException.class)
	public Result errorHandler2(BaseException ex) {
		StackTraceElement[] stackTrace = ex.getStackTrace();
		Exception exception = new Exception(ex.getMessage());
		exception.setStackTrace(stackTrace);
		logger.error(ex.fillInStackTrace().toString(), exception);
		Result responseEntity = new Result();
		responseEntity.setCode(ex.getCode());
		switch (responseEntity.getCode()) {
		case 1001: {
			responseEntity.setMsg("data not found.");
		}
			break;
		case 1002: {
		}
			break;
		default:
			responseEntity.setMsg(ex.getMsg());
		}
		return responseEntity;
	}
}
